<template>
    <el-container>
        <el-header style="text-align: right; font-size: 15px" height="50px">
            <el-row type="flex" justify="end">
                <el-col :xs="0" :sm="8" :md="4" :lg="4" :xl="4">
                    <el-input
                            v-model="search"
                            size="medium"
                            placeholder="输入姓名关键字搜索"/>
                </el-col>
                <el-col :xs="22" :sm="14" :md="4" :lg="4" :xl="4">
                    <el-dropdown size="medium" split-button type="primary" trigger="click" @command="handleCommand">
                        <i class="fa fa-bars"></i>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="new">新增</el-dropdown-item>
                            <el-dropdown-item :disabled="current_staff==null" command="update">更新
                            </el-dropdown-item>
                            <el-dropdown-item command="batchUpdate">批量更新
                            </el-dropdown-item>
                            <el-dropdown-item :disabled="current_staff==null" command="delete">删除
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <span>{{current_staff==null?'':current_staff.name}}</span>
                </el-col>
            </el-row>
        </el-header>

        <el-main>
            <el-table
                    :data="staff.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
                    @selection-change="handleSelectionChange"
                    max-height="760" row-class-name="myRowStyle" @row-click="staffClick">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="150" sortable >
                </el-table-column>
                <el-table-column label="性别" width="120" sortable>
                    <template slot-scope="scope">
                        <label class="label label-warning fa fa-female" v-show="scope.row.sex==0">女</label>
                        <label class="label label-primary fa fa-male" v-show="scope.row.sex==1">男</label>
                        <label class="label label-danger fa fa-question" v-show="scope.row.sex==2">未指定</label>
                    </template>
                </el-table-column>
                <el-table-column prop="id_card" label="身份证" width="250" sortable>
                </el-table-column>
                <el-table-column prop="card_num" label="卡号" width="250" sortable>
                </el-table-column>
                <el-table-column prop='building.name' label="宿舍楼" width="120" sortable>
                    <template slot-scope="scope">
                        <a :href="scope.row.building?'/dorm#/dorm_list/'+scope.row.building.id:'#'">{{scope.row.building==null?'':scope.row.building.name}}</a>
                    </template>
                </el-table-column>
                <el-table-column label="宿舍号" width="160" sortable>
                    <template slot-scope="scope">
                        <label class="label label-primary">{{scope.row.dorm==null?'':scope.row.dorm.code}}</label>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                    <template slot-scope="scope">
                        <label :class="'label label-'+(scope.row.status==1?'success':'default')">{{scope.row.status==1?'在职':'离职'}}</label>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="300" sortable>
                </el-table-column>
            </el-table>
            <el-dialog :title="oprtName+'员工信息'" width="40%"
                       :visible.sync="dialogFormVisible">
                <el-form :model="form" v-loading="loading" :rules="rules" ref="form">
                    <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="form.name" :disabled="isBatchUpdate"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                        <el-col :span="24">
                            <el-radio-group v-model="form.sex">
                                <el-radio :label="0">女</el-radio>
                                <el-radio :label="1">男</el-radio>
                                <el-radio :label="2">未指定</el-radio>
                            </el-radio-group>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="身份证" :label-width="formLabelWidth" prop="id_card">
                        <el-input v-model="form.id_card" :disabled="isBatchUpdate"></el-input>
                    </el-form-item>
                    <el-form-item label="部门" :label-width="formLabelWidth" prop="department_id">
                        <model-list-select :list="departments" option-value="id" option-text="name"
                                           v-model="form.department_id"></model-list-select>
                    </el-form-item>
                    <el-form-item label="卡号" :label-width="formLabelWidth" prop="card_num">
                        <el-input v-model="form.card_num" :disabled="isBatchUpdate"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
                        <el-radio-group v-model="form.status">
                            <el-radio :label="0">离职</el-radio>
                            <el-radio :label="1">在职</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
                        <el-input v-model="form.remark" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleStaff()">{{oprtName}}</el-button>
                </div>
            </el-dialog>
        </el-main>
    </el-container>
</template>
<script>
    export default{
        props: ['department_id'],
        data(){
            var checkProv = function (val) {
                var pattern = /^[1-9][0-9]/;
                var provs = {
                    11: "北京",
                    12: "天津",
                    13: "河北",
                    14: "山西",
                    15: "内蒙古",
                    21: "辽宁",
                    22: "吉林",
                    23: "黑龙江 ",
                    31: "上海",
                    32: "江苏",
                    33: "浙江",
                    34: "安徽",
                    35: "福建",
                    36: "江西",
                    37: "山东",
                    41: "河南",
                    42: "湖北 ",
                    43: "湖南",
                    44: "广东",
                    45: "广西",
                    46: "海南",
                    50: "重庆",
                    51: "四川",
                    52: "贵州",
                    53: "云南",
                    54: "西藏 ",
                    61: "陕西",
                    62: "甘肃",
                    63: "青海",
                    64: "宁夏",
                    65: "新疆",
                    71: "台湾",
                    81: "香港",
                    82: "澳门"
                };
                if (pattern.test(val)) {
                    if (provs[val]) {
                        return true;
                    }
                }
                return false;
            };
            var checkDate = function (val) {
                var pattern = /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
                if (pattern.test(val)) {
                    var year = val.substring(0, 4);
                    var month = val.substring(4, 6);
                    var date = val.substring(6, 8);
                    var date2 = new Date(year + "-" + month + "-" + date);
                    if (date2 && date2.getMonth() == (parseInt(month) - 1)) {
                        return true;
                    }
                }
                return false;
            };
            var checkCode = function (val) {
                var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var code = val.substring(17);
                if (p.test(val)) {
                    var sum = 0;
                    for (var i = 0; i < 17; i++) {
                        sum += val[i] * factor[i];
                    }
                    if (parity[sum % 11] == code.toUpperCase()) {
                        return true;
                    }
                }
                return false;
            };
            var checkID = function (rule, value, callback) {
                if (checkCode(value)) {
                    var date = value.substring(6, 14);
                    if (checkDate(date)) {
                        if (checkProv(value.substring(0, 2))) {
                            callback();
                        } else {
                            return callback(new Error("身份证号上的省份不存在"));
                        }
                    } else {
                        return callback(new Error("身份证号上的出生日期不正确"));
                    }
                } else {

                    return callback(new Error("身份证号格式不正确"));
                }
            };
            return {
                current_dpt_id:1,
                departments:'',
                staff: [],
                current_staff: null,
                search: '',
                loading: false,
                form: {
                    name: '',
                    dorm_id: '',
                    department_id: '',
                    card_num: '',
                    id_card: '',
                    sex: 2,
                    status: 1,
                    remark: ''
                },
                dialogFormVisible: false,
                isEdit: false,
                isBatchUpdate: false,
                oprtName: '添加',
                formLabelWidth: '100px',
                rules: {
                    name: [
                        {required: true, message: '请务必填写姓名', trigger: 'blur'},
                        {min: 2, max: 10, message: '姓名长度2-10个字符', trigger: 'blur'}],
                    id_card: [
                        {required: true, message: '请务必填写身份证', trigger: 'blur'},
                        {validator: checkID, trigger: 'blur'}
                    ]
                },
                selectedIds:[],
                copyIds:[],
            }
        },
        created(){
            axios.get('api/v1/department').then(result => {
                this.departments = result.data;
                this.departments.push({id:'',name:'未指定'});
            });
            this.getstaff(this.department_id);
        },
        watch: {
            'department_id': function (to, from) {
                this.getstaff(to);
            }
        },
        methods: {
            getstaff(department_id){
                this.$emit('departmentIdChange');//解决人为刷新页面时，默认选中宿舍菜单失去焦点
                if(department_id == 'null'){
                    this.form.department_id = '';
                    department_id='';
                }else{
                    this.form.department_id = parseInt(department_id);
                }
                axios.get('api/v1/staff?department_id=' + department_id).then(
                    result => {
                        this.staff = result.data;
                    });
                this.current_staff = null;
            },
            staffClick(row){
                this.current_staff = row;
            },
            updateStaff(){
                axios.put('api/v1/staff/' + this.current_staff.id, this.form)
                    .then(result => {
                        if (result.error) {
                            this.$notify.error({
                                message: '更新职工信息失败',
                            });
                        } else {
                            this.$notify.success({
                                message: '更新职工信息成功',
                            });

                            this.getstaff(this.department_id);
                            this.dialogFormVisible = false;
                        }
                    })
                    .catch(error => {
                        if(error.response){
                            console.log(error.response);
                        }
                        this.$notify.error({
                            message: '发生异常,更新职工信息失败',
                        });
                    });
            },
            storeStaff(){
                console.log(this.form);
                axios.post('api/v1/staff', this.form).then(result => {
                    if (result.error) {
                        this.$notify.error({
                            message: '创建职工失败'
                        });
                    } else {
                        this.$notify.success({
                            message: '创建职工成功'
                        });
                        this.getstaff(this.form.department_id);
                        this.dialogFormVisible = false;
                        this.$refs['form'].resetFields();
                    }
                }).catch(error => {
                    if(error.response){
                        console.log(error.response);
                    }
                    this.$notify.error({
                        message: '发生异常,创建职工信息失败',
                    });
                });
            },
            handleStaff(){
                if (this.isBatchUpdate) {
                    var batchUpdate={ids:this.copyIds,updateData:{
                        department_id:this.form.department_id,
                        sex:this.form.sex,
                        status:this.form.status,
                        remark:this.form.remark,
                    }};
                    console.log(batchUpdate);
                    var url=this.department_id=='null'?'api/v1/staff/batchUpdate':'api/v1/staff/'+this.department_id+'/batchUpdate';
                    axios.put(url, batchUpdate)
                        .then(result => {
                            if (result.error) {
                                this.$notify.error({message: '批量更新员工信息失败'});
                            } else {
                                this.$notify.success({message: '批量更新员工信息成功'});
                                this.dialogFormVisible = false;
                                this.getstaff(this.department_id);
                            }
                        })
                        .catch(error => {
                            if(error.response){
                                console.log(error.response);
                            }
                            this.$notify.error({
                                message: '发生异常,批量更新员工失败'
                            });
                        });

                } else {
                    this.$refs['form'].validate((valid) =>{
                        if (valid) {
                            this.loading = true;
                            if (this.isEdit) {
                                this.updateStaff();
                            } else {
                                this.storeStaff();
                            }
                            this.loading = false;
                        } else {
                            this.$notify.error({message: '请按要求填写要提交的数据'});
                        }
                    });
                }
            },
            deleStaff(){
                axios.delete('api/v1/staff/' + this.current_staff.id, this.form)
                    .then(result => {
                        if (result.error) {
                            this.$notify.error({
                                message:'删除员工信息失败',
                            });
                        } else {
                            this.$notify.success({
                                message: '删除员工信息成功',
                            });
                            this.getstaff(this.form.department_id);
                            this.dialogFormVisible = false;
                        }
                    })
                    .catch(error => {
                        if(error.response){
                            console.log(error.response);
                        }
                        this.$notify.error({
                            message: '发生异常,删除员工信息失败'
                        });
                    });
                this.centerDialogVisible = false;
            },
            handleCommand(cmd){
                switch (cmd) {
                    case 'new':
                        this.isEdit = false;
                        this.isBatchUpdate=false;
                        this.oprtName = '添加';
                        this.dialogFormVisible = true;
                        break;
                    case 'update':
                        this.isEdit = true;
                        this.isBatchUpdate=false;
                        this.oprtName = '更新';
                        this.form = this.current_staff;
                        this.dialogFormVisible = true;
                        break;
                    case 'batchUpdate':
                        if(this.selectedIds.length<1){
                            this.$alert('请选择要更新的数据');
                            return;
                        }
                        this.copyIds=_.cloneDeep(this.selectedIds);
                        this.isEdit = true;
                        this.isBatchUpdate=true;
                        this.oprtName = '批量更新';
                        this.dialogFormVisible = true;
                        break;
                    case 'delete':
                        this.deleStaff();
                        break;
                }
            },
            handleSelectionChange(val) {
                this.selectedIds = val.map(function (o) {
                    return o.id;
                });
            }
        }

    }
</script>
